'use client'

import { useSession } from 'next-auth/react'
import { redirect } from 'next/navigation'
import GroupManagement from '@/components/groups/GroupManagement'
import StudentGroupView from '@/components/groups/StudentGroupView'
import {useEffect, useState} from "react";

export default function GroupsPage() {
  const { data: session } = useSession()
  const [loading, setLoading] = useState(false)
  const [experiments, setExperiments] = useState([])
  const [error, setError] = useState<Error | null>(null)
  const [stuLoading, setStuLoading] = useState(false)
  const [students, setStudents] = useState([])
  const [stuError, setStuError] = useState<Error | null>(null)
  const [sError, setSError] = useState<Error | null>(null)
  const [sELoading, setSELoading] = useState(false)
  const [studentExperiments, setStudentExperiments] = useState([])

  
  if (!session?.user) {
    redirect('/login')
  }

  const fetchExperiments = async () => {
    setLoading(true)
    console.log('开始获取实验列表...')

    try {
      const response = await fetch('/api/experiments/group')

      if (!response.ok) {
        throw new Error('获取实验列表失败')
      }

      const data = await response.json()
      setExperiments(data)
      console.log('成功获取实验列表:', data)

    } catch (err: any) {
      console.error('获取实验列表失败:', err)
      setError(err.message || '获取实验列表失败')
      setExperiments([])
    } finally {
      setLoading(false)
    }
  }

  const fetchStudents = async () => {
    setStuLoading(true)
    console.log('开始获取学生列表...')

    try {
      const response = await fetch('/api/users/students')

      if (!response.ok) {
        throw new Error('获取学生列表失败')
      }

      const data = await response.json()
      setStudents(data)
      console.log('成功获取学生列表:', data)

    } catch (err: any) {
      console.error('获取学生列表失败:', err)
      setStuError(err.message || '获取学生列表失败')
      setStudents([])
    } finally {
      setStuLoading(false)
    }
  }

  const fetchStudentsExperiments = async () => {
    setSELoading(true)
    console.log('开始获取学生实验列表...')

    try {
      const response = await fetch('/api/experiments/student')

      if (!response.ok) {
        throw new Error('获取学生实验列表失败')
      }

      const data = await response.json()
      setStudentExperiments(data)
      console.log('成功获取学生实验列表:', data)

    } catch (err: any) {
      console.error('获取学生列表失败:', err)
      setSError(err.message || '获取学生列表失败')
      setStudentExperiments([])
    } finally {
      setSELoading(false)
    }
  }

  // 根据角色获取数据
  if (session.user.role === 'TEACHER' || session.user.role === 'ADMIN') {
    // 获取所有实验
    useEffect(() => {
      fetchExperiments()
      fetchStudents()
    }, [session])

    return (
      <div className="py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="sm:flex sm:items-center">
            <div className="sm:flex-auto">
              <h1 className="text-2xl font-semibold text-gray-900">学生分组管理</h1>
              <p className="mt-2 text-sm text-gray-700">
                管理实验的学生分组，分配实验任务给特定学生或小组。
              </p>
            </div>
          </div>

          <GroupManagement
            experiments={experiments}
            students={students}
            currentUserId={session.user.id}
          />
        </div>
      </div>
    )
  } else if (session.user.role === 'STUDENT') {
    // 获取学生所在的所有实验和分组信息
    useEffect(() => {
      fetchStudentsExperiments()
    }, [session])

    return (
      <div className="py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="sm:flex sm:items-center">
            <div className="sm:flex-auto">
              <h1 className="text-2xl font-semibold text-gray-900">我的分组</h1>
              <p className="mt-2 text-sm text-gray-700">
                查看您在各个实验中的分组情况。
              </p>
            </div>
          </div>
          <StudentGroupView experiments={studentExperiments} currentUserId={session.user.id} />
        </div>
      </div>
    )
  } else {
    // 其他角色或未定义角色，重定向到首页
    redirect('/')
  }
} 